Random

int

import random
random.randint(1,3)

k unique samples

import random
random.sample(tags_id, 3)

Print

print 会自动换行,print(end="")会取消换行,end为结束后缀

遍历文件

os.walk()

Python method walk() generates the file names in a directory tree by walking the tree either top-down or bottom-up.

  for root,dirs,files in os.walk(path):
        for fname in files:
            if filename in fname:
                result.append([id,fname])

string check contains

str = "Messi is the best soccer player"
>>> "soccer" in str
True
>>> "football" in str
False

三引号

三引号让程序员从引号和特殊字符串的泥潭里面解脱出来,自始至终保持一小块字符串的格式是所谓的WYSIWYG(所见即所得)格式的。

print('''I'm going to the movies''')

html = '''
<HTML><HEAD><TITLE>
Friends CGI Demo</TITLE></HEAD>
<BODY><H3>ERROR</H3>
<B>%s</B><P>
<FORM><INPUT TYPE=button VALUE=Back
ONCLICK="window.history.back()"></FORM>
</BODY></HTML>
'''
print(html)

元组和列表

元组是不可变的, 而列表是可变的。

我们可以修改列表的值,但是不能修改元组的值。
由于列表是可变的,我们不能将列表用作字典中的key。 但可以使用元组作为字典key。

同构与异构

习惯上元组多用于用于存储异构元素,异构元素即不同数据类型的元素,比如(ip,port)。 另一方面,列表用于存储异构元素,这些元素属于相同类型的元素,比如[int1,in2,in3]。

list

reverse sublist

a[start:stop:step] # start through not past stop, by step
step为-1的时候是reverse order
a[:-11:-1] # the last 10 items, reversed

sort

The sort() method doesn't return any value. Rather, it changes the original list.
list.sort(key=..., reverse=...)
If you want a function to return the sorted list rather than change the original list, use sorted().
sorted(list, key=..., reverse=...)

paramter

reverse - If True, the sorted list is reversed (or sorted in Descending order)
key - function that serves as a key for the sort comparison

JSON

Python list(dict) to json string

json.dumps 用于将 Python 对象编码成 JSON 字符串。

import json
data = [ { 'b' : 2, 'd' : 4, 'a' : 1, 'c' : 3, 'e' : 5 } ]
json = json.dumps(data)
print(json)

[{"b": 2, "d": 4, "a": 1, "c": 3, "e": 5}]

json string to python list(dict)_

json.loads 用于解码 JSON 数据。该函数返回 Python 字段的数据类型。

import json
jsonData = '{"a":1,"b":2,"c":3,"d":4,"e":5}'
text = json.loads(jsonData)  #将string转换为dict
print(text)

打包并压缩

把当前目录下所有文件打包压缩成a.tar.zip

tar -zcvf a.tar.zip ./

解压
-C 指定目录

tar -zxvf a.tar.zip -C ../

爬虫

request模块:

requests是python实现的简单易用的HTTP库,官网地址:http://cn.python-requests.org/zh_CN/latest/
requests.get(url)可以发送一个http get请求,返回服务器响应内容。

BeautifulSoup库:

BeautifulSoup 是一个可以从HTML或XML文件中提取数据的Python库。网址:https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/
BeautifulSoup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,其中一个是 lxml。
BeautifulSoup(markup, "html.parser")或者BeautifulSoup(markup, "lxml"),推荐使用lxml作为解析器,因为效率更高。

通过tag标签逐层查找:

soup.select("body a")

获取属性

tag.get('href')
或者
tag['href']
如果不确定某个属性是否存在时,用 tag.get('attr') 方法去获取它,跟获取Python字典的key一样
tag['class']
KeyError: 'class'
print(tag.get('class'))
None

        link = star['link']
         headers = { 
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
    }

        #!!!请在以下完成对每个选手图片的爬取,将所有图片url存储在一个列表pic_urls中!!!    
        pic_urls = []
        response = requests.get(link,headers=headers)

        #将一段文档传入BeautifulSoup的构造方法,就能得到一个文档的对象, 可以传入一段字符串
        soup = BeautifulSoup(response.text,'lxml')
            
        pic_list_url = soup.select(".summary-pic a")[0]['href']
        tags1 = soup.select('div .shixian_zhaobiao')
        tag1 = tags1[0]
        tag2 = tag1.find(name = 'dl')
        tags2 = tag2.find_all(name = 'a')

jsonp to json

response_json = response[ response.index("(") + 1 : response.rindex(") }
catch")]

或者get请求的时候,去掉callback=,则会返回json

动态请求

如果数据是动态加载,可以在浏览器network里查看请求的api

写入文件

With the "With" statement, you get better syntax and exceptions handling.
"The with statement simplifies exception handling by encapsulating common
preparation and cleanup tasks."
In addition, it will automatically close the file. The with statement provides
a way for ensuring that a clean-up is always used.

with open('output.txt', 'w') as file:  # Use file to refer to the file object

    file.write('Hi there!')

with 省去写exception handler和close file

pandas

read csv

df = pd.read_csv('tag.csv')

dataframe

cut

将age按0-5,5-20...bins 分成 既几部分,label为[婴儿,青年...]
ages = np.array([1,5,10,40,36,12,58,62,77,89,100,18,20,25,30,32]) #年龄数据
pd.cut(ages, [0,5,20,30,50,100], labels=[u"婴儿",u"青年",u"中年",u"壮年",u"老年"])

参考

value_counts

df.value_counts() 以Series形式返回指定列的不同取值的频率,默认按频率从高到低排序

groupby

df['name'].groupby(df['zone'])
s = grouped.count()
zone
中国上海      5
中国北京      9
df = pd.DataFrame({'Animal': ['Falcon', 'Falcon',
                              'Parrot', 'Parrot'],
                   'Max Speed': [380., 370., 24., 26.]})
df
   Animal  Max Speed
0  Falcon      380.0
1  Falcon      370.0
2  Parrot       24.0
3  Parrot       26.0
df.groupby(['Animal']).mean()
        Max Speed
Animal
Falcon      375.0
Parrot       25.0

matplot

size

plt.figure(figsize=(12, 12))

%matplotlib inline

%matplotlib inline 可以在Ipython编译器里直接使用,功能是可以内嵌绘图,并且可以省略掉plt.show()这一步

pie

参数:

x :(每一块)的比例,如果sum(x) > 1会使用sum(x)归一化;
labels :(每一块)饼图外侧显示的说明文字;
explode :(每一块)离开中心距离;
startangle :起始绘制角度,默认图是从x轴正方向逆时针画起,如设定=90则从y轴正方向画起;
shadow :在饼图下面画一个阴影。默认值:False,即不画阴影;

## draw pie
labels = ["45-50kg",'<45kg','50-55kg','55kg']
plt.pie(weightsfreq.values, explode=(0.1,0.1,0.1,0.1),labels=labels, shadow=True,autopct='%.2f%%',startangle=90)
plt.axis('equal')
plt.legend(loc="upper right",fontsize=10,bbox_to_anchor=(1.1,1.05),borderaxespad=0.3)
plt.title('''《青春有你2》选手体重分布''',fontsize = 10)
plt.savefig('/home/aistudio/work/result/bar_result03.jpg')

参考

正圆

plt.axis('equal')

string format

python >3.6

>>> name = 'hoxis'
>>> age = 18
>>> f"hi, {name}, are you {age}"
'hi, hoxis, are you 18'

百分号

%%表示百分号

>>> print('数据的比例是:%.2f%%' %(scale * 100))
数据的比例是:10.00%
>>> print('数据的比例是:%d%%' %(scale * 100))
数据的比例是:10%

参考

词云

 根据词频绘制词云图
    参数 word_f:统计出的词频结果
    # 生成对象
    mask = np.array(Image.open("alice_mask.png"))
    wc = WordCloud(mask=mask, font_path='SimHei.ttf', mode='RGBA', background_color=None)
    wc.fit_words(word_f)
    
    
    # 显示词云
    plt.imshow(wc, interpolation='bilinear')
    plt.axis("off")
    plt.show()
    
    # 保存到文件
    wc.to_file('wordcloud.png')

matlibplot 加载中文字体

	#下载中文字体
	wget https://mydueros.cdn.bcebos.com/font/simhei.ttf 
	#在操作系统中创建字体目录fonts(可能已经有
	mkdir .fonts
	# 复制字体文件到该路径
	cp simhei.ttf .fonts/
	#复制字体到当前使用的conda环境中的matplotlib下的指定路径
	cp simhei.ttf /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/matplotlib/mpl-data/fonts/ttf/
	# Linux系统默认字体文件路径
	ls /usr/share/fonts/
	# 查看系统可用的ttf格式中文字体
	fc-list :lang=zh | grep ".ttf"
	 # 设置显示中文
    matplotlib.rcParams['font.san-serif'] = ['SimHei']
    # 解决负号'-'显示为方块的问题
    matplotlib.rcParams['axes.unicode_minus'] = False

如果没成功,尝试

from matplotlib.font_manager import _rebuild
_rebuild() #reload一下

jieba 分词

   jieba.load_userdict('name.txt') #name.txt 为用户自定义分词
   seg = jieba.lcut(text,cut_all=False)

停用词

stopwords = [line.strip() for line in open(file_path, encoding="UTF-8").readlines()]
for word in sentence:
        if word not in stopwords:
            if len(word) > 1:
                counts[word] = counts.get(word, 0) + 1

字典 .get(key,value) value为如果不存在返回的值,counts.get(word, 0): word不存在于counts中则返回 0
中文常用停用词词表

多进程

多进程共同的全局变量,需要使用特殊方式声明:

from multiprocessing import Process, Value, Array, Manager

def f(n, a):
    n.value = 3.1415927
    for i in range(len(a)):
        a[i] = -a[i]

if __name__ == '__main__':
    num = Value('d', 0.0)
    arr = Array('i', range(10))
    lis =  Manager().list()
    p = Process(target=f, args=(num, arr))
    p.start()
    p.join()

    print(num.value)
    print(arr[:])

多进程list 使用前需转换回普通list, list(lis)
.join() 可以等待进程执行结束后再输出

多进程的一个大坑:broken pipe

解决方案不要在主线程外使用shared object,这样主线程使用的时候修改,会影响子线程的这个object
解决方案:移除主线程的修改,或者把修改放到子线程跑完之后
解释

.join()

主线程等待子线程跑完。python默认是先执行完主线程

    process= []
    for c_id in content_ids:
        # 每个进程爬取一个视频下的评论
        p = Process(target=getMovieinfo,args=(c_id,))
        process.append(p)
        p.start()
    
    #等待所有线程任务结束。
    for p in process:
        p.join()
    print("总共获取了",len(comments),'条评论')

这样主线程就会阻塞了
参考

I am a real pikachu!